package com.imooc.course.server.service.impl;

import com.imooc.course.server.dao.CourseContentFileDao;
import com.imooc.course.server.dto.CourseContentFileDto;
import com.imooc.course.server.entity.CourseContentFile;
import com.imooc.course.server.entity.CourseContentFileExample;
import com.imooc.course.server.service.CourseContentFileService;
import com.imooc.course.server.utils.CopyUtil;
import com.imooc.course.server.utils.UuidUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

@Service("courseContentFileService")
public class CourseContentFileServiceImpl implements CourseContentFileService {

    private static final Logger log = LoggerFactory.getLogger(CourseContentFileServiceImpl.class);

    @Resource(name = "courseContentFileDao")
    private CourseContentFileDao courseContentFileDao;

    /**
     * 列表查询
     * @param courseId
     */
    @Override
    public List<CourseContentFileDto> getList(String courseId) {
        CourseContentFileExample example = new CourseContentFileExample();
        example.createCriteria().andCourseIdEqualTo(courseId);
        List<CourseContentFile> courseContentFileList = courseContentFileDao.selectByExample(example);
        List<CourseContentFileDto> courseContentFileDtoList = CopyUtil.copyList(courseContentFileList, CourseContentFileDto.class);
        return courseContentFileDtoList;
    }

    /**
     * 保存，id有值为更新，id无值为新增
     * @param courseContentFileDto
     */
    @Override
    public void save(CourseContentFileDto courseContentFileDto) {
        CourseContentFile copy = CopyUtil.copy(courseContentFileDto, CourseContentFile.class);
        String id = courseContentFileDto.getId() != null ? courseContentFileDto.getId().trim() : courseContentFileDto.getId();
        if (StringUtils.isEmpty(id)) {
            this.addCourseContentFile(copy);
        }else{
            this.updateCourseContentFile(copy);
        }
    }

    private void updateCourseContentFile(CourseContentFile copy) {
        courseContentFileDao.updateByPrimaryKeySelective(copy);
    }

    private void addCourseContentFile(CourseContentFile copy) {
        copy.setId(UuidUtil.getShortUuid());
        courseContentFileDao.insertSelective(copy);
    }

    /**
     * 删除
     * @param id
     */
    @Override
    public void delete(String id) {
        courseContentFileDao.deleteByPrimaryKey(id);
    }
}
